package com.rawchen.util;

import com.github.pagehelper.PageHelper;
import com.rawchen.model.vo.Result;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

public class WebUtil {
	public static void renderString(HttpServletResponse response, Result result) {
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setCharacterEncoding("utf-8");
			try (PrintWriter out = response.getWriter()) {
				out.write(JacksonUtils.toJsonString(result));
				out.flush();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 处理数据分页
	 *
	 * @param date     时间段，数组长度必须为0或2
	 * @param pageNum  页码
	 * @param pageSize 每页数量
	 * @return 解析后的时间段，保证长度为2
	 */
	public static String[] pageProcess(String[] date, Integer pageNum, Integer pageSize) {
		if (date.length != 0 && date.length != 2)
			throw new NegativeArraySizeException("数组长度必须为0或2");
		String startDate = null;
		String endDate = null;
		if (date.length == 2) {
			startDate = date[0];
			endDate = date[1];
		}
		String orderBy = "create_time desc";
		PageHelper.startPage(pageNum, pageSize, orderBy);
		return new String[]{startDate, endDate};
	}
}
